﻿#define _CRT_SECURE_NO_WARNINGS 1

#include"SList.h"


//打印
void SLTPrint(SLTNode* phead)
{
	SLTNode* pcur = phead;
	while (pcur)
	{
		printf("%d->", pcur->data);
		pcur = pcur->Next;
	}
	printf("NULL\n");
}

//尾部插入
void SLTPushBack(SLTNode** pphead, SLTDataType x)
{
	assert(pphead);
	SLTNode* newNode = (SLTNode*)malloc(sizeof(SLTNode));
	newNode->data = x;
	newNode->Next = NULL;
	//如果链表为空
	if (*pphead == NULL)
	{
		*pphead = newNode;
		return;
	}
	//链表不为空
	SLTNode* ptile = *pphead;
	while (ptile->Next)
	{
		ptile = ptile->Next;
	}
	ptile->Next = newNode;
}

//头部插⼊
void SLTPushFront(SLTNode** pphead, SLTDataType x)
{
	assert(pphead);
	SLTNode* newNode = (SLTNode*)malloc(sizeof(SLTNode));
	newNode->data = x;
	newNode->Next = *pphead;
	*pphead = newNode;
}

//尾部删除
void SLTPopBack(SLTNode** pphead)
{
	assert(pphead);
	//链表不能为空
	assert(*pphead);
	//链表只有一个节点
	if ((*pphead)->Next == NULL)
	{
		free(*pphead);
		*pphead = NULL;
		return;
	}
	SLTNode* ptile = *pphead;
	while (ptile->Next->Next)
	{
		ptile = ptile->Next;
	}
	ptile->Next = NULL;
	free(ptile->Next);

}

//头部删除
void SLTPopFront(SLTNode** pphead)
{
	assert(pphead);
	assert(*pphead);
	SLTNode* newHead = (*pphead)->Next;
	free(*pphead);
	*pphead = NULL;
	*pphead = newHead;
}

//查找
SLTNode* SLTFind(SLTNode* phead, SLTDataType x)
{
	assert(phead);
	SLTNode* pcur = phead;
	while (pcur)
	{
		if (pcur->data == x)
		{
			return pcur;
		}
		pcur = pcur->Next;
	}
	return NULL;
}

//在指定位置之前插⼊数据
void SLTInsert(SLTNode** pphead, SLTNode* pos, SLTDataType x)
{
	assert(pphead && pos);
	assert(*pphead);

	SLTNode* newNode = (SLTNode*)malloc(sizeof(SLTNode));
	newNode->data = x;
	newNode->Next = NULL;
	//pos刚好是头节点
	if (pos == *pphead)
	{
		//头插
		SLTPushFront(pphead, x);
	}
	//pos不是头节点
	SLTNode* prev = *pphead;
	while (prev->Next != pos)
	{
		prev = prev->Next;
	}

	prev->Next = newNode;
	newNode->Next = pos;
}

//删除pos节点
void SLTErase(SLTNode** pphead, SLTNode* pos)
{
	assert(pphead && pos);
	assert(*pphead);
	//pos刚好是头节点，没有前驱，执行头删
	if (pos == *pphead)
	{
		SLTPopFront(pphead);
		return;
	}

	SLTNode* prev = *pphead;
	while (prev->Next != pos)
	{
		prev = prev->Next;
	}
	prev->Next = pos->Next;
	free(pos);
	pos = NULL;
}

//在指定位置之后插⼊数据
void SLTInsertAfter(SLTNode* pos, SLTDataType x)
{
	assert(pos);

	SLTNode* newNode = (SLTNode*)malloc(sizeof(SLTNode));
	newNode->data = x;
	newNode->Next = NULL;

	newNode->Next = pos->Next;
	pos->Next = newNode; 
}

//删除pos之后的节点
void SLTEraseAfter(SLTNode* pos)
{
	assert(pos && pos->Next);
	SLTNode* del = pos->Next;
	pos->Next = del->Next;
	free(del);
	del = NULL;
}

//销毁链表
void SListDesTroy(SLTNode** pphead)
{
	assert(*pphead);
	assert(pphead);
	SLTNode* pcur = *pphead;
	while (pcur)
	{
		SLTNode* next = pcur->Next;
		free(pcur);
		pcur = next;
	}
	*pphead = NULL;
}